<!-- 测试线宽地图 -->
<template>
  <div id="mapbox-container">
    <button class="view-style" @click="getView">获取视角{{ zoomValue }}</button>
    <button class="view-style" style="left: 150px;" @click="changeSchool">切换校区</button>
    <div class="style-name">
      <a-button @click.stop="openFile">
        <DownloadOutlined />
        导入模型
      </a-button>
      <input ref="exportGltf" type="file" accept=".glb" hidden @change="exportModel" />
      <a-button style="margin-left: 20px" @click="exportJsonFile">
        <template #icon>
          <upload-outlined />
        </template>
        导出模型配置文件
      </a-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import mapboxgl from '../../components/mapbox/mapbox.js'
import U from 'mapbox-gl-utils'
import axios from 'axios'
import api from '../../api/geoserver'
import * as turf from '@turf/turf'
// import MapboxDraw from '@mapbox/mapbox-gl-draw'
// import MapboxLanguage from '@mapbox/mapbox-gl-language'
import { Threebox, THREE } from 'threebox-plugin'
import { message } from 'ant-design-vue'
import {
  DownloadOutlined,
  UploadOutlined
} from '@ant-design/icons-vue'
import { exportJson } from '../../utils/xingutils.js'

defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
let map = null
let xiaoqu = true
let molayersData

const exportGltf = ref(null)

const zoomValue = ref('15.3')

// const emit = defineEmits(['onload'])
const { proxy } = getCurrentInstance()
const path = import.meta.env.VITE_APP_PATH

onMounted(() => {
  loadConfig()
})

// 同步加载底图配置信息
async function loadConfig() {
  const style = await axios.get(import.meta.env.VITE_APP_PATH + 'config/white-v4.json').catch((err) => console.log(err))
  // console.log(style)
  initMap(style.data)
}

// 根据配置信息初始化地图
function initMap(style) {
  // 初始化创建mapbox地图 ======'name': '昆明医科大学',

  map = new mapboxgl.Map({
    container: 'mapbox-container',
    // style: style,
    style: 'mapbox://styles/mapbox/light-v11',
    center: [116.58814186526291, 39.8958210127098],
    zoom: 14.5,
    pitch: 3.2,
    bearing: -92
  })
  // mapboxgl.setRTLTextPlugin(
  //   'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js'
  // )
  // map.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}))
  // map.addControl(new MapboxDraw(), 'bottom-right')

  // 等map创建完成后加载建筑图层
  map.on('load', function () {
    // Start the animation.
    // rotateCamera(0)

    // 初始化mapbox工具类
    U.init(map)

    // 创建天空盒
    map.setFog({
      'horizon-blend': 0.3,
      color: '#f8f0e3'
      // 'high-color': '#add8e6',
      // 'space-color': '#d8f2ff',
      // 'star-intensity': 0.0
    })
    // 抛出map创建完成事件
    // emit('onload', map)
    loadDatas()
    // addChartletLyer()
    // loadLayerJson()
  })
  map.on('click', function (e) {
    // console.log("----click----");
    // console.log(e.point);
    // console.log(e.lngLat);
  })
  map.on('dblclick', function (e) {
    // console.log("----dblclick----");
  })
  map.on('zoom', function () {
    zoomValue.value = map.getZoom().toFixed(1)
  })
}

// 加载图层数据
async function loadDatas() {
  const gsonline = turf.lineString([
    // [116.59879595, 39.89664171],
    // [116.5986717, 39.89666261],
    // [116.59845011, 39.8967033],
    // [116.59822853, 39.89674739],
    // [116.59801115, 39.8967937],
    // [116.59780068, 39.89684064],
    // [116.59763333, 39.89687921],
    // [116.59731113, 39.89695625],
    // [116.59713508, 39.89699872],
    // [116.59673796, 39.89709448],
    // [116.59635517, 39.89718667],
    // [116.59543407, 39.89740892],
    // [116.59427369, 39.89768908],
    // [116.59316579, 39.89795618],
    // [116.59204817, 39.8982258],
    // [116.59092802, 39.89849675],
    // [116.58923804, 39.89890439],
    // [116.58856897, 39.89906471],
    // [116.58823185, 39.89914184],
    // [116.58782895, 39.89922778],
    // [116.58744885, 39.89930006],
    // [116.58678085, 39.89940347],
    // [116.5863369, 39.89945522],
    // [116.5857559, 39.89950292],
    // [116.58519192, 39.89952749],
    // [116.58462346, 39.89953284],
    // [116.5840741, 39.89952423],
    // [116.58331796, 39.8995008],
    // [116.58104876, 39.89942425],
    // [116.58043856, 39.89940805],
    // [116.5800868, 39.89940463],
    // [116.57972216, 39.8994081],
    // [116.57942718, 39.89941664],
    // [116.57908413, 39.8994336],
    // [116.57870473, 39.89945937],
    // [116.57866246, 39.89946294]
    // [116.61322442, 39.89545417],//大弧线
    // [116.61357355, 39.895436],
    // [116.61389777, 39.8954199],
    // [116.61422509, 39.89540458],
    // [116.61455151, 39.89539436],
    // [116.61487034, 39.89539065],
    // [116.61516373, 39.89539519],
    // [116.61546184, 39.89540924],
    // [116.61575114, 39.89543238],
    // [116.61604035, 39.89546508],
    // [116.61639025, 39.89551685],
    // [116.61670851, 39.89557655],
    // [116.61699794, 39.89564188],
    // [116.61728927, 39.8957181],
    // [116.6175743, 39.8958032],
    // [116.61789369, 39.89591228],
    // [116.61816692, 39.89601736],
    // [116.61844676, 39.89613728],
    // [116.61870176, 39.89625811],
    // [116.61894966, 39.89638745],
    // [116.61922071, 39.89654335],
    // [116.61947022, 39.89670024],
    // [116.61962352, 39.89680959]
    [116.62422254, 39.90157596],//斜直线
    [116.62822254, 39.90257596],
    [116.62866323, 39.90627436]

  ])

  const endindex = gsonline.geometry.coordinates.length - 1

  console.log('gsonline', gsonline)

  addLineLlayer(gsonline, 1)

  // 线的起点的左边
  const lsl = turf.transformRotate(gsonline, -90, {
    pivot: gsonline.geometry.coordinates[0]
  })

  // addLineLlayer(lsl, 2)

  // 线的起点的左边
  const lsr = turf.transformRotate(gsonline, 90, {
    pivot: gsonline.geometry.coordinates[0]
  })

  // addLineLlayer(lsr, 3)

  // 线的终点的左边
  const lel = turf.transformRotate(gsonline, 90, {
    pivot: gsonline.geometry.coordinates[endindex]
  })

  // addLineLlayer(lel, 4)

  // 线的终点的右边
  const ler = turf.transformRotate(gsonline, -90, {
    pivot: gsonline.geometry.coordinates[endindex]
  })
  // addLineLlayer(ler, 5)

  const buffered = turf.buffer(gsonline, 100, {
    units: 'meters'
  })

  // 构建buffer为点featureCollection
  const bufferedtoline = turf.polygonToLine(buffered)
  const pointsarr = []
  bufferedtoline.geometry.coordinates.forEach((coord) => {
    const point = turf.point(coord)
    pointsarr.push(point)
  })
  const points = turf.featureCollection(pointsarr)
  console.log('points1111111111111111111', points)

  // 遍历找出4个点(垂线与buffer相交的点)
  const four_gline = [lel, lsl, lsr, ler]
  const intersectpointarr = []
  four_gline.forEach((i) => {
    const intersects = turf.lineIntersect(i, buffered)
    const intersectpoint = intersects.features[0]
    intersectpointarr.push(intersectpoint)
  })
  console.log('遍历找出4个点(垂线与buffer相交的点)', intersectpointarr)

  const four_index = []
  intersectpointarr.forEach((i) => {
    const nearest = turf.nearestPoint(i, points)
    four_index.push(nearest.properties.featureIndex)
    // console.log(nearest.geometry.coordinates)
  })

  console.log('找出buffer点集合中与相交点最接近的点', four_index)
  const splicetop = four_index[0] - four_index[3]
  const splicebtm = four_index[2] - four_index[1]
  console.log('截取点数', splicetop, splicebtm)
  const bufferedcoordarry = buffered.geometry.coordinates[0]
  console.log(bufferedcoordarry)
  bufferedcoordarry.splice(four_index[3] + 1, splicetop - 1)
  console.log(bufferedcoordarry)
  bufferedcoordarry.splice(four_index[1] + 2 - splicetop, splicebtm - 1)
  console.log(bufferedcoordarry)
  const jiego = {
    type: 'Feature',
    properties: {},
    geometry: {
      type: 'LineString',
      coordinates: bufferedcoordarry
    }
  }
  addLineLlayer(jiego, 6)
}

function addLineLlayer(datas, i) {
  map.addSource('source_line' + i, {
    type: 'geojson',
    data: datas
  })

  map.addLayer({
    id: 'test_line' + i,
    type: 'line', //设置当前图层类型 此为边
    source: 'source_line' + i,
    'layout': {
      'line-join': 'round',
      'line-cap': 'round'
    },
    'paint': {
      'line-color': '#888',
      'line-width': 1
    }
  })
}

function getView() {
  console.log('中心点', map.getCenter())
  console.log('倾斜角', map.getPitch())
  console.log('旋转角', map.getBearing())
  console.log('放大层级', map.getZoom().toFixed(1))
}

function changeSchool() {
  if (xiaoqu) {
    map.setCenter([102.71052463307672, 25.05258088822093])
  } else {
    map.setCenter([102.82799237023596, 24.847129783439215])
  }
  xiaoqu = !xiaoqu
}

function openFile() {
  exportGltf.value.click()
}

// 上传文件模型改变
const key = 'updatable'

function exportModel(file) {
  const f = file.target.files[0]

  if (f?.name.includes('.glb')) {
    loadPathModel(f)
    message.loading({ content: '模型上传中...', key })
  } else {
    message.error('请打开规定格式文件！')
  }
}

// 加载模型
function loadPathModel(fileInfo) {
  const name = fileInfo.name,
    dataURL = URL.createObjectURL(fileInfo),
    { lng, lat } = map.getCenter()
  console.log('信息', name, dataURL, lng, lat)
  const model = {
    name: name.split('.')[0],
    type: 'glb',
    zqobj: dataURL,
    obj: dataURL,
    units: 'meters',
    scale: 1,
    rotation: {
      x: 90,
      y: 0,
      z: 0
    },
    anchor: 'center',
    position: [lng, lat, 0]
  }

  window.tb.loadObj(model, function (mo) {
    const soldier = mo.setCoords(model.position)

    soldier.uuid = model.name
    soldier.traverse((e) => {
      if (e.material) {
        e.material.format = THREE.RGBAFormat
        if (model.belong === 'zdmodels.json') {
          e.material.color.offsetHSL(0, 0, -0.3)
          e.material.emissive = e.material.color
          e.material.emissiveMap = e.material.map
        }
      }
    })
    window.tb.add(soldier)
    message.success({ content: '上传成功!', key, duration: 2 })
  })
}

// 导出模型调整位置后的配置文件
function exportJsonFile() {
  console.log('导出文件', window.tb)
  const modelList = window.tb.scene.children[0].children,
    modelJson = {
      models: [],
      type: 'modelCollection',
      opacityZoom: 18
    }

  for (const modelObj of modelList) {
    const modelInfo = {
      name: modelObj.userData.name,
      type: modelObj.userData.type,
      obj: './model/' + modelObj.userData.name + '.glb',
      belong: modelObj.userData.belong,
      units: modelObj.userData.units,
      scale: modelObj.userData.scale,
      offsetHSL: modelObj.userData.offsetHSL || 0,
      campus: modelObj.userData.campus || '呈贡校区',
      rotation: modelObj.userData.rotation,
      anchor: modelObj.userData.anchor,
      position: modelObj.userData.position
    }

    modelInfo.position = modelObj.coordinates
    modelInfo.rotation.y =
      modelInfo.rotation.y +
      Number((modelObj.rotation.z * 180 / Math.PI).toFixed(0))
    // console.log("整理模型信息", modelInfo);
    modelJson.models.push(modelInfo)
  }
  console.log('模型json', modelJson)
  exportJson(modelJson, 'kmykdxmodels.json')
}

// 加载配置文件中图层信息
async function loadLayerJson() {

}


</script>

<style lang='scss' scoped>
#mapbox-container {
  width: 100vw !important;
  height: 100vh !important;
}

.view-style {
  position: fixed;
  top: 50px;
  left: 50px;
  z-index: 10;
}

.style-name {
  position: fixed;
  top: 100px;
  left: 50px;
  z-index: 10;
  color: #eb9c8a;
}
</style>

